/*
	Anonymous Image Board Image Downloader - program for downloading pictures from AIB
	Copyright (C) 2011-2012 Metallhead <Metallhead@megabox.ru>

	HomePage:    http://code.google.com/p/aibid/

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef DOWNLOADING_H
#define DOWNLOADING_H

#include <QObject>
#include <QNetworkReply>
#include <QStandardItemModel>
#include <QModelIndex>
#include <QNetworkAccessManager>
#include <QReadWriteLock>
#include <QVector>
#include <QTimer>
#include <QXmlStreamReader>
#include <QThread>
#include <QMutex>
#include <QMessageBox>
#include <QtSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include "common.h"



extern int connectionsOpened;
extern QMap<uint, QString> hashCodes;

extern QVector<detectorStruct> detectors;

//enum imageTypes { JPG = 1, PNG = 2, GIF = 4 };



class downloading : public QObject
{
    Q_OBJECT

signals:
	//void infoChanged();
	void imagesCountChanged();
	void statusChanged();
	void threadIsFree();
	void changeTimerState(int, bool);
	void folderInfoUpdate();
private:
	//public
	downloading(QString newUrl, QString newPath, bool hash, int limit, imageTypes imagesTypes);
	~downloading();
	void prepare();
	void setStatus(QString newStatus);
	int threadsLimit;
	int dbUpdateInterval;

	QStringList * links;
	QMutex mutex, dbMutex;
	void dbCheck();
	//private

	QString dataBaseName;
	QString status;

	QNetworkAccessManager * manager;
    QString url,path,siteName;
	QSqlDatabase * db;
	int imageCount,imagesDownloaded, row;
	void incImageCount();
	void incImagesDownloaded();
	bool checkImage(QByteArray * arr);
	bool checkHash(QByteArray * arr);
	void addUrlsAndCodes(int count);
	bool alowedType(QString imageName);
	imageTypes imagesTypes;
//	void addUrl(QString url);
//	void addHash(uint hash);

	int connectionNumber;
    QNetworkReply * reply;
	QVector<QNetworkReply *> * replies;
	bool noLimit;
	void createDb();
	QStringList allFolderLinks;
	QStringList linksToAdd, hashcodesToAdd;
	int similarImages;
    bool stop;
	bool hashCheck;
	//bool jpg, png, gif;

	friend class downloads;
private slots:
    void downloadImage(QNetworkReply * imageReply);
	void startDownloadingImage();
};

#endif // DOWNLOADING_H
